package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.auth.bo.UserAuthResetBo;
import com.cskaoyan.bean.auth.bo.WXAuthRegisterBo;
import com.cskaoyan.bean.dashboardvo.DashBoardVo;
import com.cskaoyan.bean.data.*;
import com.cskaoyan.bean.usermodelbo.*;
import com.cskaoyan.bean.usermodelvo.*;
import com.cskaoyan.bean.wx_userindexVO.OrderBean;
import com.cskaoyan.bean.wx_userindexVO.UserIndexVO;
import com.cskaoyan.mapper.*;
import com.cskaoyan.util.CskaoyanPageHelper;
import com.cskaoyan.util.StringUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: yudefu
 * @date 2021年06月04日  19:23
 * @description: 用户管理模块
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    DashBoardMapper dashBoardMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    RegionMapper regionMapper;

    @Autowired
    CollectMapper collectMapper;

    @Autowired
    FootPrintMapper footPrintMapper;

    @Autowired
    SearchHistoryMapper searchHistoryMapper;

    @Autowired
    FeedbackMapper feedbackMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    CommentMapper commentMapper;

    /**
     * 首页模块
     */
    @Override
    public DashBoardVo getDashBoardData() {

        DashBoardVo dashBoardVo = new DashBoardVo();

        //获得商品数量
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria goodsCriteria = goodsExample.createCriteria();
        goodsCriteria.andDeletedEqualTo(false);
        long goodsNums = goodsMapper.countByExample(goodsExample);

        dashBoardVo.setGoodsTotal(goodsNums);

        //获得用户数量
        UserExample userExample = new UserExample();
        UserExample.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andDeletedEqualTo(false);
        long userNums = userMapper.countByExample(userExample);

        dashBoardVo.setUserTotal(userNums);

        //获得商品产品数量
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria goodsProductcriteria = goodsProductExample.createCriteria();
        goodsProductcriteria.andDeletedEqualTo(false);
        long goodsProductNums = goodsProductMapper.countByExample(goodsProductExample);
        dashBoardVo.setProductTotal(goodsProductNums);

        //获得订单数量
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria orderCriteria = orderExample.createCriteria();
        orderCriteria.andDeletedEqualTo(false);
        long orderNums = orderMapper.countByExample(orderExample);
        dashBoardVo.setOrderTotal(orderNums);

//        Integer orderTotal = dashBoardMapper.getOrderTotal();

        return dashBoardVo;
    }


    //获取会员用户列表
    @Override
    public BaseData<User> getUserList(UserReq userReq) {

        //执行查询之前 → 使用分页插件 → 会在执行过程中拼接上sql语句
//        PageHelper.startPage(userReq.getPage(), userReq.getLimit());
        CskaoyanPageHelper.startPage(userReq);


        UserExample userExample = new UserExample();

        userExample.setOrderByClause(userReq.getSort() + " " + userReq.getOrder());

        UserExample.Criteria criteria = userExample.createCriteria();

        if (!(StringUtils.isEmpty(userReq.getUsername()))) {
            criteria.andUsernameLike("%" + userReq.getUsername() + "%");
        }

        if (!(StringUtils.isEmpty(userReq.getMobile()))) {
            criteria.andMobileEqualTo(userReq.getMobile());
        }
        criteria.andDeletedEqualTo(false);

        List<User> users = userMapper.selectByExample(userExample);
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        long total = userPageInfo.getTotal();


        return BaseData.ok(users, total);
    }


    //获取收获地址
    @Override
    public BaseData<Address> getAddressList(AddressReq addressReq) {

        //使用分页插件
//        PageHelper.startPage(addressReq.getPage(), addressReq.getLimit());
        CskaoyanPageHelper.startPage(addressReq);

        AddressExample addressExample = new AddressExample();

        //设置顺序
        addressExample.setOrderByClause(addressReq.getSort() + " " + addressReq.getOrder());

        AddressExample.Criteria criteria = addressExample.createCriteria();

        if (!(StringUtils.isEmpty(addressReq.getName()))) {
            criteria.andNameLike("%" + addressReq.getName() + "%");
        }

        if (!(StringUtils.isEmpty(addressReq.getUserId()))) {
            Integer id = Integer.parseInt(addressReq.getUserId());
            criteria.andUserIdEqualTo(id);
        }
        criteria.andDeletedEqualTo(false);

        List<Address> addresses = addressMapper.selectByExample(addressExample);

        List<AddressVo> addressVoList = new ArrayList<>();

        for (Address address : addresses) {

            Integer provinceId = address.getProvinceId();
            Integer cityId = address.getCityId();
            Integer areaId = address.getAreaId();

            Region province = regionMapper.selectByPrimaryKey(provinceId);
            Region city = regionMapper.selectByPrimaryKey(cityId);
            Region area = regionMapper.selectByPrimaryKey(areaId);

            AddressVo addressVo = new AddressVo(area.getName(), address.getId(), address.getName(), address.getUserId(), address.getProvinceId(), address.getCityId(), address.getAreaId(), address.getAddress(), province.getName(), city.getName(), address.getMobile(), address.getIsDefault());
            addressVoList.add(addressVo);
        }

        PageInfo<Address> addressPageInfo = new PageInfo<>(addresses);
        long total = addressPageInfo.getTotal();

        return BaseData.ok(addressVoList, total);
    }


    //获取会员收藏列表
    @Override
    public BaseData<Collect> getCollectList(CollectReq collectReq) {

        //使用分页插件
//        PageHelper.startPage(collectReq.getPage(), collectReq.getLimit());
        CskaoyanPageHelper.startPage(collectReq);

        CollectExample collectExample = new CollectExample();

        collectExample.setOrderByClause(collectReq.getSort() + " " + collectReq.getOrder());

        CollectExample.Criteria criteria = collectExample.createCriteria();

        if (!(StringUtils.isEmpty(collectReq.getUserId()))) {
            Integer userId = Integer.parseInt(collectReq.getUserId());
            criteria.andUserIdEqualTo(userId);
        }
        if (!(StringUtils.isEmpty(collectReq.getValueId()))) {
            Integer valueId = Integer.parseInt(collectReq.getValueId());
            criteria.andValueIdEqualTo(valueId);
        }
        criteria.andDeletedEqualTo(false);

        List<Collect> collects = collectMapper.selectByExample(collectExample);
        PageInfo<Collect> collectPageInfo = new PageInfo<>(collects);
        long total = collectPageInfo.getTotal();


        return BaseData.ok(collects, total);
    }


    //获取会员足迹
    @Override
    public BaseData<FootPrint> getFootPrintList(FootPrintReq footPrintReq) {

        //分页插件
//        PageHelper.startPage(footPrintReq.getPage(), footPrintReq.getLimit());
        CskaoyanPageHelper.startPage(footPrintReq);

        FootPrintExample footPrintExample = new FootPrintExample();

        footPrintExample.setOrderByClause(footPrintReq.getSort() + " " + footPrintReq.getOrder());

        FootPrintExample.Criteria criteria = footPrintExample.createCriteria();

        if (!(StringUtils.isEmpty(footPrintReq.getUserId()))) {
            int userId = Integer.parseInt(footPrintReq.getUserId());
            criteria.andUserIdEqualTo(userId);
        }
        if (!(StringUtils.isEmpty(footPrintReq.getGoodsId()))) {
            int goodsId = Integer.parseInt(footPrintReq.getGoodsId());
            criteria.andGoodsIdEqualTo(goodsId);
        }
        criteria.andDeletedEqualTo(false);

        List<FootPrint> footPrints = footPrintMapper.selectByExample(footPrintExample);

        PageInfo<FootPrint> footPrintPageInfo = new PageInfo<>(footPrints);
        long total = footPrintPageInfo.getTotal();


        return BaseData.ok(footPrints, total);
    }


    //获取搜索历史
    @Override
    public BaseData<SearchHistory> getHistoryList(HistoryReq historyReq) {

        //使用分页插件
//        PageHelper.startPage(historyReq.getPage(), historyReq.getLimit());
        CskaoyanPageHelper.startPage(historyReq);

        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();

        searchHistoryExample.setOrderByClause(historyReq.getSort() + " " + historyReq.getOrder());

        SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();

        if (!(StringUtils.isEmpty(historyReq.getUserId()))) {
            int userId = Integer.parseInt(historyReq.getUserId());
            criteria.andUserIdEqualTo(userId);
        }
        if (!(StringUtils.isEmpty(historyReq.getKeyword()))) {
            criteria.andKeywordLike("%" + historyReq.getKeyword() + "%");
        }
        criteria.andDeletedEqualTo(false);

        List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);

        PageInfo<SearchHistory> searchHistoryPageInfo = new PageInfo<>(searchHistories);
        long total = searchHistoryPageInfo.getTotal();


        return BaseData.ok(searchHistories, total);
    }

    @Override
    public BaseData<Feedback> getFeedbackList(FeedbackReq feedbackReq) {

        //使用分页插件
//        PageHelper.startPage(feedbackReq.getPage(), feedbackReq.getLimit());
        CskaoyanPageHelper.startPage(feedbackReq);

        FeedbackExample feedbackExample = new FeedbackExample();
        feedbackExample.setOrderByClause(feedbackReq.getSort() + " " + feedbackReq.getOrder());

        FeedbackExample.Criteria criteria = feedbackExample.createCriteria();

        if (!(StringUtils.isEmpty(feedbackReq.getUsername()))) {
            criteria.andUsernameLike("%" + feedbackReq.getUsername() + "%");
        }
        if (!(StringUtils.isEmpty(feedbackReq.getId()))) {
            int id = Integer.parseInt(feedbackReq.getId());
            criteria.andIdEqualTo(id);
        }

        criteria.andDeletedEqualTo(false);

        List<Feedback> feedbacks = feedbackMapper.selectByExample(feedbackExample);
        PageInfo<Feedback> feedbackPageInfo = new PageInfo<>(feedbacks);
        long total = feedbackPageInfo.getTotal();

        return BaseData.ok(feedbacks, total);
    }


    @Override
    public UserIndexVO userIndex(Integer id) {
        int uncomment = 0;
        int unpaid = 0;
        int unrecv = 0;
        int unship = 0;
        OrderBean orderBean = new OrderBean();
        UserIndexVO userIndexVO = new UserIndexVO();
        //去用户关联的订单表里获取未付款的订单数量
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
//        criteria.andUserIdEqualTo(id);
        criteria.andUserIdEqualTo(id).andDeletedEqualTo(false); // 要选择未删除的订单 by 王得昭
        List<Order> orders = orderMapper.selectByExample(orderExample);

        for (Order order : orders) {
            if (order.getOrderStatus() == 101) {
                unpaid += 1;
            } else if (order.getOrderStatus() == 201) {
                unship += 1;
            } else if (order.getOrderStatus() == 301) {
                unrecv += 1;
            } else if (order.getOrderStatus() == 401 || order.getOrderStatus() == 402) {
                uncomment += order.getComments();
            }
        }
        orderBean.setUnpaid(unpaid);


        orderBean.setUnship(unship);

        orderBean.setUnrecv(unrecv);

        //去用户关联的订单表里表里获取未评论的评论数量
        for (Order order : orders) {
            if (order.getOrderStatus() == 401 || order.getOrderStatus() == 402) {
                uncomment += 1;
            }
        }

        orderBean.setUncomment(uncomment);
        userIndexVO.setOrder(orderBean);
        return userIndexVO;
    }

    @Override
    public User selectUser(String username) {
        User user = userMapper.selectUser(username);
        return user;
    }

    @Override
    public int getLastLoginTime(String username) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());
        Timestamp ts = Timestamp.valueOf(time);
        return userMapper.insertLastLoginTime(username, ts);
    }

    @Override
    public int getLastLoginIp(String ip, String username) {
        return userMapper.insertLastLoginIp(username);
    }

    @Override
    public void changePassword(UserAuthResetBo bo) {
        String password = bo.getPassword();
        String mobile = bo.getMobile();
        User user = new User();
        user.setPassword(password);
        UserExample example = new UserExample();
        user.setUpdateTime(new Date());
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andMobileEqualTo(mobile);
        userMapper.updateByExampleSelective(user, example);
    }

    @Override
    public int insertUser(WXAuthRegisterBo registerBo) {
        User user = new User();

        String password = registerBo.getPassword();
        String username = registerBo.getUsername();
        String wxCode = registerBo.getWxCode();
        String mobile = registerBo.getMobile();

        user.setPassword(password);
        user.setUsername(username);
        user.setMobile(mobile);
        user.setWeixinOpenid(wxCode);
        user.setNickname("小白用户" + mobile); // 初始nickname 叫 "小白用户188-0140-6178"
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());
        Timestamp timestamp = Timestamp.valueOf(time);
        user.setAddTime(timestamp);

        int i = userMapper.insertSelective(user);
        return i;
    }


    /*
    @Override
    public UserData selectUserData(Integer page, Integer limit, String sort, String order) {

        //执行查询之前 → 使用分页插件 → 会在执行过程中拼接上sql语句
        PageHelper.startPage(page, limit);

        //username = "test1" nickname like 测试用户
        //criteria不能设为全局变量
        //每个service的方法都来创建example对象
        UserExample userExample = new UserExample();


        //排序信息
        userExample.setOrderByClause(sort + " " + order);

        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo("test1")
                .andNicknameLike("%测试用户%");


            if(mobile != null && !"".equals(mobile){
                criteria.andMobileLike("%" + mobile + "%");
            }



        List<User> users = userMapper.selectByExample(userExample);
//        int total = users.size(); //total并不是我们当前查询出来的结果的数据量 → 满足条件的总的数据量
        //比如采用了分页，total并不是每页的数据，而是总的

        //可以获得分页信息
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        long total = userPageInfo.getTotal();

        UserData userData = new UserData();
        userData.setTotal(total);
        userData.setItems(users);
        return userData;
    }
    */


}
